package com.littlebee.storysuper.activity;


import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.littlebee.storysuper.R;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * 设置宝宝信息
 */
public class SettingBabyInfoActivity extends BaseActivity implements View.OnClickListener {
    private EditText phoneNumber;
    private EditText babyName;
    private TextView bobyBrith;
    private RadioGroup sex;
    private EditText address;
    private RadioGroup role;
    private RadioButton male, female, father, mother;
    private Button btn_setting;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    //获取日期格式器对象
    Calendar calendar = Calendar.getInstance(Locale.CHINA);
    String dateStr = "";
    TextView logOutTv;
    boolean isFirst;
    CommonToolbar toolbar;
    private Button btn_newfunction;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_setting_baby_info;
    }

    @Override
    public void initView() {
        super.initView();
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        phoneNumber = (EditText) findViewById(R.id.et_1);
        babyName = (EditText) findViewById(R.id.et_2);
        bobyBrith = (TextView) findViewById(R.id.et_3);
        sex = (RadioGroup) findViewById(R.id.rg1);
        address = (EditText) findViewById(R.id.et_5);
        role = (RadioGroup) findViewById(R.id.rg2);
        btn_setting = (Button) findViewById(R.id.btn_setting);
        male = (RadioButton) findViewById(R.id.male);
        female = (RadioButton) findViewById(R.id.female);
        father = (RadioButton) findViewById(R.id.father);
        mother = (RadioButton) findViewById(R.id.mother);
        logOutTv = (TextView) findViewById(R.id.logout_tv);
        logOutTv.setOnClickListener(this);

        btn_newfunction = (Button) findViewById(R.id.btn_newfunction);
        btn_newfunction.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        User user = Utils.getUserEntry();
        phoneNumber.setText(user.getMobile());
        bobyBrith.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upTime();
            }
        });
        btn_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setInfo();
            }
        });
        getInfo();
    }

    /**
     * 获取宝宝信息
     */
    public void getInfo() {
        User user = Utils.getUserEntry();
        Map<String, String> map = new HashMap<>();
        map.put("phoneId", user.getMobile());
        NetWorkUtils.post(SettingBabyInfoActivity.this, "getbabyinfo", map, false, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                //LogUtils.i("XHX", "XHXSUCC:" + result);
                try {
                    String nameS = /**URLDecoder.decode(*/resObj.getJSONObject("response").getString("babyname")/**)*/;
                    babyName.setText(nameS);
                    dateStr = resObj.getJSONObject("response").getString("babybirthday");
                    bobyBrith.setText(dateStr);
                    String addressS = /**URLDecoder.decode(*/resObj.getJSONObject("response").getString("babyaddress")/**)*/;
                    address.setText(addressS);
                    int sexS = resObj.getJSONObject("response").getInt("babysex");
                    if (sexS == 1) {
                        male.setChecked(true);
                    } else {
                        female.setChecked(true);
                    }
                    int roleS = resObj.getJSONObject("response").getInt("myrole");
                    if (roleS == 1) {
                        father.setChecked(true);
                    } else {
                        mother.setChecked(true);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String result, String code, String msg) {

            }
        });
    }

    /**
     * 设置宝宝信息
     */
    public void setInfo() {
        User user = Utils.getUserEntry();
        //phoneId=18611697983&babyname=susan&babybirthday=2017-03-02&babysex=1&babyaddress=湖北省武汉市武昌区汉南大道223号&myrole=1

        if (TextUtils.isEmpty(babyName.getText().toString().trim())) {
            ToastUtil.displayShortToast("宝宝昵称不能为空");
            return;
        }
        if (TextUtils.isEmpty(dateStr)) {
            ToastUtil.displayShortToast("生日不能为空");
            return;
        }
        if (TextUtils.isEmpty(address.getText().toString().trim())) {
            ToastUtil.displayShortToast("地址不能为空");
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("phoneId", user.getMobile());
        map.put("babyname", babyName.getText().toString());
        map.put("babybirthday", dateStr);
        RadioButton radioButton = (RadioButton) findViewById(sex.getCheckedRadioButtonId());
        if (radioButton.getText().toString().equals("男")) {
            map.put("babysex", "1");
        } else {
            map.put("babysex", "2");

        }

        map.put("babyaddress", address.getText().toString());
        RadioButton radioButton1 = (RadioButton) findViewById(role.getCheckedRadioButtonId());
        if (radioButton1.getText().toString().equals("爸爸")) {
            map.put("myrole", "1");
        } else {
            map.put("myrole", "2");

        }

        NetWorkUtils.post(SettingBabyInfoActivity.this, "setbabyinfo", map, false, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                //LogUtils.i("XHX", "XHXSUCC:" + result);
                ToastUtil.displayShortToast("设置宝宝信息成功");
                //finish();
                isFirst = false;
                changeEndle();
            }

            @Override
            public void onError(String result, String code, String msg) {

            }
        });

    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);

        toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.me_info_txt));
        changeEndle();
        toolbar.setOnRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFirst = !isFirst;

                changeEndle();
            }
        });


    }

    private void changeEndle() {
        //设置焦点不可点击
        if (isFirst) {
            btn_setting.setVisibility(View.VISIBLE);
            babyName.setEnabled(true);
            bobyBrith.setEnabled(true);
            male.setEnabled(true);
            female.setEnabled(true);
            father.setEnabled(true);
            mother.setEnabled(true);
            address.setEnabled(true);
            toolbar.setRightText("完成");

        } else {
            btn_setting.setVisibility(View.GONE);
            babyName.setEnabled(false);
            bobyBrith.setEnabled(false);
            male.setEnabled(false);
            female.setEnabled(false);
            father.setEnabled(false);
            mother.setEnabled(false);
            address.setEnabled(false);
            toolbar.setRightText("编辑");

        }

    }

    /**
     * 时间选择器
     */
    private void upTime() {
        //生成一个DatePickerDialog对象，并显示。显示的DatePickerDialog控件可以选择年月日，并设置
        DatePickerDialog datePickerDialog = new DatePickerDialog(SettingBabyInfoActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //修改日历控件的年，月，日
                //这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateTimeShow();
            }

        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void updateTimeShow() {
        dateStr = df.format(calendar.getTime());
        bobyBrith.setText(dateStr);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logout_tv:
                // TODO: 2017/8/15
                UserInfo myInfo = JMessageClient.getMyInfo();
                if (myInfo != null) {
                    JMessageClient.logout();

                }
                Utils.saveUserEntry(null);
                finish();
                break;
            case R.id.btn_newfunction:
                startActivity(new Intent(this, VoiceCallingActivity.class));
                break;
        }

    }
}
